from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import redirect, render
from django.utils.deprecation import MiddlewareMixin


class UserInfo:
    def __init__(self, role, name, nickname, id):
        self.role = role
        self.name = name
        self.nickname = nickname
        self.id = id
        self.menu_name = None
        self.text_list = []


class AuthMiddleware(MiddlewareMixin):

    def is_white_url(self, request):
        if request.path_info in settings.MOBILEDJ_WHITE_URL:
            return True

    def process_request(self, request):
        """ 校验用户是否登录 """
        current_name = request.path_info
        # 1. 不需要登录就可以访问的URL

        if self.is_white_url(request):
            return

        # 2. 从session中获取用户登录信息,能获取到，登录成功

        user_dict = request.session.get(settings.MOBILEDJ_SESSION_KEY)
        # 3. 未登录，跳转到登录页面
        if not user_dict:
            return redirect(settings.MOBILEDJ_LOGIN_URL)
        # 4.已登录，封装用户信息
        request.mobiledj_user = UserInfo(**user_dict)

    def process_view(self, request, callback, callback_args, callback_kwargs):
        """
        路由匹配上以后走该函数
        该函数做权限校验
        """

        if self.is_white_url(request):
            return
        url_record = [{'title': '首页', 'url': 'home'}]
        # 0.是否有公共权限
        current_name = request.resolver_match.url_name
        request.breadcrumb = url_record

        if current_name in settings.MOBILEDJ_PERMISSION_PUBLIC:
            return

        # 1.根据用户角色获取用户所具备的权限
        user_permission_dict = settings.MOBILEDJ_PERMISSION[request.mobiledj_user.role]

        # 2.获取当前用户访问的url
        current_name = request.resolver_match.url_name
        # 3.判断用户是否具备权限
        if current_name not in user_permission_dict:
            if request.is_ajax():
                return JsonResponse({'status': False, 'detail': '没有权限！'})
            else:
                return render(request, 'permission.html')

        # 4.如果有权限
        text_list = []
        text_list.append(user_permission_dict[current_name]['text'])

        menu_name = current_name
        if user_permission_dict[menu_name]['parent']:
            url_record.extend(
                [{
                    'title': user_permission_dict[user_permission_dict[menu_name]['parent']]['text'],
                    'url': user_permission_dict[menu_name]['parent']},
                    {
                        'title': user_permission_dict[menu_name]['text'],
                        'url': menu_name,
                        'class': 'active'
                    }
                ]
            )
        else:
            url_record.extend(
                [{'title': user_permission_dict[current_name]['text'],
                  'url': menu_name,
                  'class': 'active'
                  }]
            )

        while user_permission_dict[menu_name]['parent']:
            menu_name = user_permission_dict[menu_name]['parent']
            text = user_permission_dict[menu_name]['text']
            text_list.append(text)

        text_list.append('首页')
        text_list.reverse()

        # 4.1 当前菜单
        request.mobiledj_user.menu_name = menu_name

        # 4.2 路径导航
        request.breadcrumb = url_record
